// 前端生成随机验证码图片
export const createMockCaptchaImg = (domId, length) => {
  // 1. 生成4位随机字符串
  let code = "";
  let stringList = "ASDFGHJKLasdfghjkl123456789";
  for (let i = 0; i < length; i++) {
    const index = Math.floor(Math.random() * stringList.length);
    code += stringList[index];
  }
  // 2. 将生成的随机数进行Canvas绘制
  const canvas = document.getElementById(domId);
  const ctx = canvas.getContext("2d");
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // 背景颜色 (没什么必要, 直接用DOM的背景色也可以)
  // ctx.fillStyle = "#f4f4f5";
  // ctx.fillRect(0, 0, canvas.width, canvas.height);
  // 文字样式
  ctx.font = "20px Arial";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillStyle = "#000";
  ctx.fillText(code, canvas.width / 2, canvas.height / 2);
  // 3. 将绘制好的Canvas转换成图片返回
  const img = new Image();
  img.src = canvas.toDataURL("image/png");
  return img;
};

// 判断是否为空[null, undefined, ""]
export const isEmpty = (value) => {
  if ([null, undefined, ""].includes(value)) {
    return true;
  } else {
    return false;
  }
};

// 防抖
export const debounce = (callBack, delay = 500, immediate = false) => {
  let timer = null;
  return function (...args) {
    // 清除已有的定时器
    clearTimeout(timer);
    if (immediate) {
      // 如果是立即执行模式，且为第一次触发，则执行函数
      const runNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, delay);
      if (runNow) {
        callBack.apply(this, args);
      }
    } else {
      // 非立即执行模式，延迟指定时间后再执行函数
      timer = setTimeout(() => {
        callBack.apply(this, args);
      }, delay);
    }
  };
};
